import axios from 'axios'

// API 基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api'

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  error => {
    console.error('API Error:', error)
    return Promise.reject(error)
  }
)

// ==================== 统一 API v1 ====================

export const unifiedApi = {
  // 服务状态检查
  getStatus: () => api.get('/v1/status'),
  
  // 天气服务
  getWeather: (latitude, longitude) => 
    api.get('/v1/weather', { params: { latitude, longitude } }),
  
  // POI搜索
  searchPOIs: (latitude, longitude, radius = 3000) => 
    api.get('/v1/pois', { params: { latitude, longitude, radius } }),
  
  // 步行路线
  getRoute: (startLat, startLng, endLat, endLng) => 
    api.get('/v1/route', { 
      params: { start_lat: startLat, start_lng: startLng, end_lat: endLat, end_lng: endLng } 
    }),
  
  // AI景点介绍
  generateIntroduction: (poiName, poiCategory, poiDescription = '', weather = null) => 
    api.post('/v1/ai/introduction', { 
      poi_name: poiName, 
      poi_category: poiCategory, 
      poi_description: poiDescription,
      weather 
    }),
  
  // TTS语音合成
  textToSpeech: (text, voice = 'alloy') => 
    api.post('/v1/ai/tts', { text, voice }),
  
  // 音乐生成
  generateMusic: (poiName, poiCategory, weatherCondition = '晴', mood = 'relaxing') => 
    api.post('/v1/ai/music', { 
      poi_name: poiName, 
      poi_category: poiCategory, 
      weather_condition: weatherCondition, 
      mood 
    }),
  
  // 开始散步（综合接口）
  startWalk: (latitude, longitude) => 
    api.post('/v1/walk/start', { latitude, longitude })
}

// ==================== 原有 API（保持兼容） ====================

// 用户相关
export const userApi = {
  login: (code) => api.post('/auth/wechat-login', { code }),
  getProfile: () => api.get('/user/profile'),
  setHomeLocation: (location) => api.put('/user/home-location', location)
}

// 路径规划相关
export const routeApi = {
  searchPOIs: (latitude, longitude, radius = 3000) => 
    api.post('/route/search-pois', { 
      location: { latitude, longitude, accuracy: 10.0 }, 
      radius_meters: radius 
    }),
  generateRoute: (startLocation, poiId) => 
    api.post('/route/generate', { 
      start_location: { ...startLocation, accuracy: startLocation.accuracy || 10.0 }, 
      target_poi_id: poiId 
    }),
  replanRoute: (currentLocation, choice, homeLocation) => 
    api.post('/route/replan', { 
      current_location: { ...currentLocation, accuracy: currentLocation.accuracy || 10.0 }, 
      choice, 
      home_location: homeLocation 
    })
}

// 会话相关
export const sessionApi = {
  start: (poiId, route) => api.post('/session/start', { poi_id: poiId, route }),
  updateLocation: (sessionId, location) => 
    api.put(`/session/${sessionId}/location`, location),
  end: (sessionId) => api.post(`/session/${sessionId}/end`),
  getStatus: (sessionId) => api.get(`/session/${sessionId}/status`),
  getHistory: () => api.get('/session/history')
}

// 天气相关
export const weatherApi = {
  getCurrent: (latitude, longitude) => 
    api.get('/weather/current', { params: { latitude, longitude } }),
  check: (latitude, longitude) => 
    api.get('/weather/check', { params: { latitude, longitude } })
}

// 景点相关
export const poiApi = {
  getIntroduction: (poiId) => api.get(`/poi/${poiId}/introduction`)
}

// AI相关
export const aiApi = {
  generateMusic: (poiId, weather, mood) => 
    api.post('/ai/generate-music', { poi_id: poiId, weather, mood })
}

// 音乐相关
export const musicApi = {
  getLibrary: () => api.get('/music/library'),
  save: (musicId) => api.post(`/music/${musicId}/save`),
  delete: (musicId) => api.delete(`/music/${musicId}`)
}

export default api
